package com.itheima.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //每次新增菜品就删除redis中的缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null, Dish::getName,name);
        //添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,lqw);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        //获取原数据的集合
        List<Dish> records = pageInfo.getRecords();

        //创建新数据的集合，将处理好的原数据集合赋值进去
        List<DishDto> list = new ArrayList<>();

        //处理原数据的集合
        records.forEach( e->{
            Long categoryId = e.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);//根据分类id查询分类表
            String categoryName = category.getName();//获取分类的名字

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(e,dishDto);
            //设置dishDto的分类名，分类名来自根据分类id查询出的分类
            dishDto.setCategoryName(categoryName);
            //将处理好的原数据集合赋值给新数据集合
            list.add(dishDto);
        });

        //将新数据的集合赋值给新分页构造器
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //每次修改菜品就删除redis中的缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }


    /**
     * 根据分类id查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish, String name){
//        //创建一个DishDto集合
        List<DishDto> dishDtoList = null;
//
//        //动态构造key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        //先从redis中查询缓存的菜品

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        System.out.println("================================="+dishDtoList);
//
        if (dishDtoList!=null){
            //如果redis中有缓存的菜品，直接返回
            return R.success(dishDtoList);
        }
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //查询条件
        lqw.eq(dish.getCategoryId()!=null ,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);

        lqw.like(name!=null,Dish::getName,name);
        //排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(lqw);

        //创建一个DishDto集合
        List<DishDto> ls1 = new ArrayList<>();

//        log.info(dishDtoList.toString());
        dishList.forEach(e->{

            DishDto dishDto = new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(e,dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(DishFlavor::getDishId,e.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list);
            ls1.add(dishDto);
        });
        //如果redis中没有缓存的菜品，就查询数据库，然后将查询出的数据存到缓存中
        redisTemplate.opsForValue().set(key,ls1,60, TimeUnit.MINUTES);
        return R.success(ls1);
    }


    /**
     * 菜品状态停售
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> stop(@RequestParam List<Long> ids){
        log.info("ids{},",ids);
        //判断当前菜品是否关联了套餐
        ids.forEach(e->{
            LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SetmealDish::getDishId,e);
            long count = setmealDishService.count(lqw);
            if (count>0){
                //关联了套餐不能删除，
                throw new CustomException("关联了套餐不能删除");
            }
            //获得页面传来的要修改的id集合
            Dish dish = dishService.getById(e);
            dish.setStatus(0);
            dishService.updateById(dish);
        });
        return R.success("修改状态成功");
    }

    /**
     * 菜品状态起售
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> use(@RequestParam List<Long> ids){
        log.info("ids{},",ids);
        //获得页面传来的要修改的id集合
        List<Dish> dishList = dishService.listByIds(ids);
        //遍历集合把其中的状态改成1
        dishList.forEach(e->{
            e.setStatus(1);
        });
        //遍历集合进行修改
        dishList.forEach(e->{
            dishService.updateById(e);
        });
        return R.success("修改状态成功");
    }

}
